package com.xyoto.community.service.impl;

import com.xyoto.community.cache.CacheInstruction;
import com.xyoto.community.entity.main.Topic;
import com.xyoto.community.mapper.main.TopicMapper;
import com.xyoto.community.service.TopicCacheService;
import com.xyoto.community.utils.RedisCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author coderFu
 * @create 2021/11/22
 */

@Slf4j
@Service
public class TopicCacheServiceImpl implements TopicCacheService {

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Autowired
    private TopicMapper topicMapper;

    private final Random random = new Random();


    @Override
    public boolean judgeTopicDynamicEnableAnonymous(Integer topicId) {
        return false;
    }

    @Override
    public boolean updateTopicDynamicAnonymousCache(Integer topicId) {
        return false;
    }

    @Override
    public Topic getTopicMessageFromCache(Integer topicId) {
        //判断缓存中是否有该话题
        boolean flag = redisCommonUtils.judgeHashExistKey(CacheInstruction.TOPIC, topicId);
        Topic topic = null;
        if (flag){
            //缓存中存在
            Object topicObj = redisCommonUtils.hget(CacheInstruction.TOPIC, topicId);
            if (topicObj != null){
                topic = (Topic)topicObj;
            }
        }else {
            //缓存中不存在
            //查询DB
            topic = topicMapper.selectOneByTopicId(topicId);
            if (topic != null){
                //加入到缓存中
                redisCommonUtils.hset(CacheInstruction.TOPIC,topicId,topic,
                        CacheInstruction.TOPIC_EXPIRE_TIME+random.nextInt((int) (CacheInstruction.TOPIC_EXPIRE_TIME*0.05)));
            }
        }
        return topic;
    }

    @Override
    @Async("taskExecutor")
    public void addTopicToCache(Topic topic) {

        //判断话题数目是否大于50000
        long count = redisCommonUtils.hlen(CacheInstruction.TOPIC);
        if (count < CacheInstruction.DYNAMIC_MAX_SAVE_COUNT){
            //存入缓存中,过期时间为 正常时间偏移百分之五
            redisCommonUtils.hset(CacheInstruction.TOPIC,topic.getId().toString(),topic,
                    CacheInstruction.TOPIC_EXPIRE_TIME+random.nextInt((int) (CacheInstruction.TOPIC_EXPIRE_TIME*0.05)));

        }
    }

    @Override
    @Async("taskExecutor")
    public void deleteTopicFromCache(Integer topicId) {
        //删除缓存中的话题信息
        redisCommonUtils.hdel(CacheInstruction.TOPIC,topicId);
    }

    @Override
    @Async("taskExecutor")
    public void updateTopicFromCache(Topic topic) {
        this.addTopicToCache(topic);
    }


}
